export function fixdata(data) {
  let o = "",
    l = 0,
    w = 10240;
  for (; l < data.byteLength / w; ++l)
    o += String.fromCharCode.apply(
      null,
      new Uint8Array(data.slice(l * w, l * w + w))
    );
  o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
  return o;
}

export function exportExcl({XLSX, data, name, fileName}) {
  const wopts = { bookType: "xlsx", bookSST: false, type: "binary" };
  const wb = {
    SheetNames: [name],
    Sheets: {},
    Props: {}
  };

  wb.Sheets[(name)] = XLSX.utils.json_to_sheet(data);
  saveAs(
    new Blob([s2ab(XLSX.write(wb, wopts))], {
      type: "application/octet-stream"
    }),
    fileName +
    "." +
    (wopts.bookType === "biff2" ? "xls" : wopts.bookType)
  );
}

export function saveAs(obj, fileName) {
  let tmpa = document.createElement("a");
  tmpa.download = fileName || "下载";
  tmpa.href = URL.createObjectURL(obj); //绑定a标签
  tmpa.click(); //模拟点击实现下载
  setTimeout(function () {
    URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
}

export function s2ab(s) {
  if (typeof ArrayBuffer !== "undefined") {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  } else {
    let buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) {
      buf[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  }
}

export function download(name, response) {
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = response
  link.download = `${name}.xls`;
  document.body.appendChild(link)
  link.click()
  window.URL.revokeObjectURL(link.href);
}
